package com.tianzheng.rzzl.base;

import static android.content.Context.NOTIFICATION_SERVICE;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.basic.library.base.BaseApplication;
import com.basic.library.bean.UserInfo;
import com.basic.library.utils.LocalData;
import com.google.gson.Gson;
import com.tianzheng.rzzl.R;
import com.tianzheng.rzzl.bean.PushInfo;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.utils.UMUtils;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.api.UPushRegisterCallback;
import com.umeng.message.entity.UMessage;

/**
 * @author yj
 * @description
 */
class PushHelper {
    private static String ObjectCategory;
    private static String ObjectId;
    private static String MessageCategory;
    private static String Badge;

    static String getString(int res) {
        return BaseApplication.getInstance().getString(res);
    }

    /**
     * 预初始化，已添加子进程中初始化sdk。
     * 使用场景：用户未同意隐私政策协议授权时，延迟初始化
     *
     * @param context 应用上下文
     */
    public static void preInit(Context context) {
        PushAgent.setup(context, getString(R.string._AppKey), getString(R.string._Secret));
        UMConfigure.preInit(context, getString(R.string._AppKey), "Umeng");
    }

    /**
     * 初始化。
     * 场景：用户已同意隐私政策协议授权时
     *
     * @param context 应用上下文
     */
    public static void init(Context context) {
        // 在此处调用基础组件包提供的初始化函数 相应信息可在应用管理 -> 应用信息 中找到 http://message.umeng.com/list/apps
        // 参数一：当前上下文context；
        // 参数二：应用申请的Appkey；
        // 参数三：渠道名称；
        // 参数四：设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机；
        // 参数五：Push推送业务的secret 填充Umeng Message Secret对应信息
        UMConfigure.submitPolicyGrantResult(context, true);//友盟隐私授权API
        UMConfigure.init(
                context,
                getString(R.string._AppKey),
                "Umeng",
                UMConfigure.DEVICE_TYPE_PHONE,
                getString(R.string._Secret)
        );

        //获取消息推送实例
        final PushAgent pushAgent = PushAgent.getInstance(context);
        //TODO:需修改为您app/src/main/AndroidManifest.xml中package值
//        pushAgent.setResourcePackageName("com.tianzheng.rzzl");
        pushAgent.setNotificationOnForeground(true);
        pushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE); //客户端允许控制声音
        pushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);//客户端允许呼吸灯点亮
        pushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);//客户端允许振动
        pushAgent.setDisplayNotificationNumber(0);
        //设备晚上23点到早上7点免打扰
        pushAgent.setNoDisturbMode(23, 0, 7, 0);

        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void launchApp(Context context, UMessage uMessage) {
                //TODO 友盟点击通知栏
                PushInfo pushInfo = new Gson().fromJson(new Gson().toJson(uMessage), PushInfo.class);
                switch (pushInfo.getExtra().getObjectCategory()){
                    case "workflow" : {
                    }
                    break;
                    default:
                }
            }
        };
        pushAgent.setNotificationClickHandler(notificationClickHandler);
        //注册推送服务，每次调用register方法都会回调该接口
        pushAgent.register(new UPushRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                Log.d("deviceToken", deviceToken);
                UserInfo userInfo = LocalData.getInstance().getUserInfo();
                if (!userInfo.getToken().isEmpty()){
                    pushAgent.setAlias(userInfo.getToken(), "PushId", (b1, s1) -> {
                        Log.d("设置Alias- ", userInfo.getToken());
                    });
                }
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.d("deviceToken", s);
            }
        });

        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @SuppressLint("WrongConstant")
            @Override
            public Notification getNotification(Context context, UMessage uMessage) {
                if (!LocalData.getInstance().isLogin()) {
                    Notification.Builder builder = new Notification.Builder(context);
                    builder.setAutoCancel(true)
                            .setVisibility(NotificationCompat.VISIBILITY_SECRET);
                    return builder.build();
                }
                BaseApplication.getInstance().getActivityLast().runOnUiThread(
                        new Runnable() {
                            @Override
                            public void run() {
//                                PushInfo pushInfo = new Gson().fromJson(new Gson().toJson(uMessage), PushInfo.class);
//                                DefNotification defNotification = new DefNotification(BaseApplication.getInstance().getActivityLast())
//                                        .setContentView(R.layout.notification)
//                                        .setDuration(3000);
//                                TextView tv_title = defNotification.findViewById(R.id.tv_title);x
//                                defNotification.show();
                            }
                        }
                );
                return super.getNotification(context, uMessage);
            }

            @Override
            public void dealWithNotificationMessage(Context context, UMessage uMessage) {
                
                super.dealWithNotificationMessage(context, uMessage);
            }

            @Override
            public void dealWithCustomMessage(Context context, UMessage uMessage) {
                super.dealWithCustomMessage(context, uMessage);
            }
        };
        pushAgent.setMessageHandler(messageHandler);
        if (isMainProcess(context)) {
            registerDeviceChannel(context);
            LocalData.getInstance().setCallback(info -> {
                pushAgent.deleteAlias(info.getToken(), "PushId", (b, s) -> {
                    Log.d("删除Alias- ", info.getToken());
                    NotificationManager notificationManager = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                        notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
                        notificationManager.cancelAll();
                    }
                    UserInfo userInfo = LocalData.getInstance().getUserInfo();
                    pushAgent.setAlias(userInfo.getToken(), "PushId", (b1, s1) -> {
                        Log.d("设置Alias- ", userInfo.getToken());
                    });
                });

            });
        }
    }

    /**
     * 注册设备推送通道（小米、华为等设备的推送）
     *
     * @param context 应用上下文
     */
    private static void registerDeviceChannel(Context context) {

    }

    /**
     * 是否运行在主进程
     *
     * @param context 应用上下文
     * @return true: 主进程；false: 子进程
     */
    public static boolean isMainProcess(Context context) {
        return UMUtils.isMainProgress(context);
    }

}
